package com.purchase.jd.job;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.purchase.jd.start.Spike;
import com.purchase.jd.commodity.JdConstants;
import com.purchase.jd.http.HttpHeaders;
import com.purchase.jd.login.Login;
import com.purchase.util.HttpUtils;
import com.purchase.util.ScheduledExecutor;

import java.net.HttpCookie;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;


/**
 * @author saw
 */
public class JdRushToPurchase implements Callable<Integer> {

    @Override
    public Integer call() throws InterruptedException {
        List<HttpCookie> cookies = Login.Cookies;
        Map<String,String> headers = HttpHeaders.getHeaders();
        while (JdConstants.COUNT.get() < JdConstants.NEED_COUNT) {
            //如果购物车内数量加上已经抢购数量小于需要抢购的数量才添加购物车
            if(JdConstants.SHOPPING_COUNT.getAndAdd(JdConstants.COUNT.get()) < JdConstants.NEED_COUNT){
                //抢购
                HttpResponse buyResponse = HttpUtils
                        .get(headers, JdConstants.BUYING_URL + JdConstants.SKU_ID, cookies);
                //更新cookie
                cookies.addAll(buyResponse.getCookies());
                //购物车数量加1
                JdConstants.SHOPPING_COUNT.getAndIncrement();
            }
            //订单信息
            HttpResponse orderResponse = HttpUtils.get(headers, JdConstants.ORDER_URL, cookies);
            //更新cookie
            cookies.addAll(orderResponse.getCookies());
            //去重cookie
            cookies = cookies.stream().distinct().collect(Collectors.toList());
            //提交订单
            JSONObject subData = new JSONObject();
            subData.put("overseaPurchaseCookies", "");
            subData.put("vendorRemarks", "[]");
            subData.put("submitOrderParam.sopNotPutInvoice", false);
            subData.put("submitOrderParam.ignorePriceChange", 1);
            subData.put("submitOrderParam.btSupport", 0);
            subData.put("submitOrderParam.isBestCoupon", 1);
            subData.put("submitOrderParam.jxj", 1);
            subData.put("submitOrderParam.trackID", Login.ticket);
            subData.put("submitOrderParam.eid", JdConstants.EID);
            subData.put("submitOrderParam.fp", JdConstants.FP);
            subData.put("submitOrderParam.needCheck", 1);

            headers.put("Referer", JdConstants.ORDER_URL);
            headers.put("origin", "https://trade.jd.com");
            headers.put("Content-Type", "application/json");
            headers.put("x-requested-with", "XMLHttpRequest");
            headers.put("upgrade-insecure-requests", "1");
            headers.put("sec-fetch-user", "?1");
            String submitOrder;
            if (JdConstants.COUNT.get() < JdConstants.NEED_COUNT) {
                submitOrder = HttpUtils.post(headers, JdConstants.SUBMIT_URL, null, cookies).body();
                System.out.println(submitOrder);
            } else {
                if(!ScheduledExecutor.EXECUTOR.isShutdown()){
                    ScheduledExecutor.EXECUTOR.shutdown();
                }
                System.out.println("已抢购" + JdConstants.COUNT + "件，请尽快完成付款");
                break;
            }
            //没获取到返回值
            if(null == submitOrder){
                //避免太快
                Thread.sleep(400);
                continue;
            }
            //
            if(submitOrder.contains("<script>")){
                System.out.println("您访问太频繁，请稍候再试");
                continue;
            }
            JSONObject jsonObject = JSON.parseObject(submitOrder);
            if(null == jsonObject.get("success")){
                //避免太快
                Thread.sleep(400);
                continue;
            }
            boolean success = jsonObject.getBoolean("success");
            //成功直接结束循环
            if (success) {
                System.out.println("抢购成功，请尽快完成付款");
                JdConstants.COUNT.getAndIncrement();
                //判断是否需要结束所有线程了
                if (JdConstants.COUNT.get() >= JdConstants.NEED_COUNT) {
                    if(!ScheduledExecutor.EXECUTOR.isShutdown()){
                        ScheduledExecutor.EXECUTOR.shutdown();
                    }
                    System.out.println("已抢购" + JdConstants.COUNT + "件，请尽快完成付款");
                    break;
                }
                break;
            }
            //不成功打印日志
            String message = jsonObject.getString("message");
            if (message != null) {
                System.out.println(message);
            }
            //避免太快
            Thread.sleep(400);
        }
        return JdConstants.COUNT.get();
    }
}
